<?php       
    //THIS IS ONLY DISPLAYED IF THEY HAVE SUBMITTED THE SEARCH FORM 
    if(isset($_GET['search'])){                 
        $name = strtoupper($_GET["q_na"]);
        $name = trim ($name);
        $name = mysqli_real_escape_string($db,$name);
            
        
        $media = strtoupper($_GET["q_me"]);
        $media = trim ($media);
        $media = mysqli_real_escape_string($db,$media);
        
        $search = "";
        if ($name != ""){ 
            $search .= "AND item.Name LIKE  '%".$name."%' ";
    
        }   
        if($media != ''){
            $search .=  " AND item.MediaId =".$media;
        }
                          
        $query = "SELECT item.* FROM item, media ";
        if(isset($_GET["q_ge"])){
        	$genre = $_GET["q_ge"];
            foreach($genre as $value){
                $query.= ",itemgenre as g".$value." ";
            }
        }
        
        $query.=" WHERE item.MediaId = media.MediaId ".$search;
        
        if(isset($genre)){
            foreach($genre as $value){
                $query.= " AND g".$value.".genreid = ".$value." AND g".$value.".MaterialId = item.MaterialId ";
            }
        
        }
        if(!empty($_GET["q_sd"][0])&&!empty($_GET["q_ed"][0])){
            $Startdate = $_GET["q_sd"];
            $Enddate = $_GET["q_ed"];
            $_GET["q_sd"] = $Startdate[0] < $Enddate[0]? $Startdate : $Enddate; 
            $_GET["q_ed"] = $Startdate[0] < $Enddate[0]? $Enddate : $Startdate; 
        
        }
        
        if(!empty($_GET["q_sd"][0])){
            if(strlen($_GET["q_sd"][0])< 4){
                $zero='';
                for($i=strlen($_GET["q_sd"][0]); $i <4; $i++){
                        
                    $zero .=0;
                    
                }
               $_GET["q_sd"][0] = $zero.$_GET["q_sd"][0];            
                
            }
        
        
    
        $query.= "AND ReleaseDate >= '".mysqli_real_escape_string($db,$_GET["q_sd"][0])."-".$_GET["q_sd"][1]."-".$_GET["q_sd"][2]."'";
        }
        if(!empty($_GET["q_ed"][0])){
            if(strlen($_GET["q_ed"][0])< 4){
                $zero='';
                for($i=strlen($_GET["q_ed"][0]); $i <4; $i++){      
                    $zero .=0;
                    
                }
               $_GET["q_ed"][0] = $zero. $_GET["q_ed"][0];            
                
            }
            
            $query.= "AND ReleaseDate <= '".$_GET["q_ed"][0]."-".$_GET["q_ed"][1]."-".$_GET["q_ed"][2]."'";
        
        }  
        //  END OF SEARCH
    }
    else if(isset($_GET["filt"])&&$_GET["filt"]=="my_borrowed"){
        if(!isset($_SESSION["User"])){
            header('Location:index.php');
            die;
        }
        $query = "SELECT item.* FROM item,borroweditem WHERE item.MaterialId = borroweditem.MaterialId AND borroweditem.UserId = ".$_SESSION["User"]["Id"];
    }
    else if(isset($_GET["filt"])&&$_GET["filt"]=="borrowed"){
        include_once 'admin_check.php';
        $query = "SELECT item.* FROM item,borroweditem WHERE item.MaterialId = borroweditem.MaterialId";
    }
    else if(isset($_GET["id"])){
        $query = 'SELECT * FROM `item` WHERE MaterialId='.$_GET["id"].'';
    }else{
        $query = 'SELECT * FROM `item`';
    }
    $column = isset($_GET["order"])? $_GET["order"]: "name";
    $query .= " ORDER BY ".$column;
    
    $stmt=$db->query($query);
    //  ECHOING OF THE MATERIAL
    while($result =$stmt -> fetch_assoc()){
        $query = "SELECT * FROM itemimage WHERE MaterialId ='".$result["MaterialId"]."';";
        $pictureselect = $db ->query($query);           
        $picture = $pictureselect -> fetch_assoc();
                        
        $image = empty($picture["file_data"])? $picture["filename"]:"material_image.php?id=".$picture["MaterialId"];
        
        $mediaselect = $db -> query("SELECT * 
                                    FROM media 
                                    WHERE MediaId = ".$result["MediaId"].";");

        $genreselect = $db -> query("SELECT genre.GenreName
                                    FROM itemgenre, genre
                                    WHERE itemgenre.MaterialId =".$result["MaterialId"]."
                                    AND itemgenre.GenreId = genre.GenreId;");

        echo'<tr>
                <td>
                    <img src="'.htmlspecialchars($image).'" width="60px" />
                </td>
                <td>
                    '. htmlspecialchars($result["Name"]).'
                    
                </td>           
                <td>';
                    if(($mediaexist =$mediaselect->num_rows) == 0){
                        echo    '<a href="update_material.php?id='.$result["MaterialId"].'">
                                    Materialet
                                    <br>
                                    mangler medie
                                </a>';

                    }else{
                        $media=$mediaselect-> fetch_assoc();
                            echo htmlspecialchars($media["MediaName"]); 
                    }
        echo    '</td>
                <td>';
                    if(($genreexist =$genreselect -> num_rows) == 0){
                        echo '<a href="update_material.php?id='.$result["MaterialId"].'">
                                Materialet
                                <br>
                                mangler genre
                            </a>';
                    }else{
                        $counter = 1;
                        while($genres=$genreselect->fetch_assoc()){
                            echo htmlspecialchars($genres["GenreName"]);
                            if($counter < $genreexist){
                                echo ', ';
                            }
                            $counter ++;
                                
                        }
                    }
        echo '</td>
              <td>';
                    $releasedate = explode('-',$result["ReleaseDate"]);
                    echo $releasedate[2].'. ';
                    switch($releasedate[1]){
                        case 1: 
                            echo 'Januar';
                            break;
                        
                        case 2:
                            echo 'Februar';
                            break;    
                            
                        case 3:
                            echo 'Marts';    
                            break;
                            
                        case 4:
                            echo 'April';    
                            break;
                            
                        case 5:
                            echo 'Maj';    
                            break;
                            
                        case 6:
                            echo 'Juni';    
                            break;
                            
                        case 7:
                            echo 'Juli';    
                            break;
                            
                        case 8:
                            echo 'August';    
                            break;
                            
                        case 9:
                            echo 'September';         
                            break;
                            
                        case 10:
                            echo 'Oktober';
                            break;
                            
                        case 11:
                            echo 'November';    
                            break;
                            
                        case 12:
                            echo 'December';                                                                                                                                                                                                                                                                                                                               
                            break;
                    }
                    echo ' '.ltrim($releasedate[0],"0");
        echo  '</td>';
        if(isset($_SESSION["User"])&&$_SESSION["User"]["Admin"]==1){
            echo '<td>
                    <a href="update_material.php?id='.$result["MaterialId"].'">
                        Ret
                    </a>
                </td>
                <td>
                    <a href="delete_confirm.php?id='.$result["MaterialId"].'" class="delete" cfm_href="delete_db.php?id='.$result["MaterialId"].'">
                        Slet
                    </a>
                </td>'; 
        }
        $query = "SELECT * FROM borroweditem WHERE MaterialId =".$result["MaterialId"];
        $borrowselect = $db ->query($query);
        $borrowed = $borrowselect -> fetch_assoc();
        if(isset($_SESSION["User"])&&$_SESSION["User"]["Admin"]==0&&$borrowed["MaterialId"]!=$result["MaterialId"]){
            echo '<td>
                    <a href="borrow_material_db.php?id='.$result["MaterialId"].'">
                        Lån
                    </a>
                </td>'; 
        }
        else if(isset($_SESSION["User"])&&$_SESSION["User"]["Admin"]==0&&$borrowed["UserId"]==$_SESSION["User"]["Id"]){
            echo'<td>
                    <a href="return_material_db.php?id='.$result["MaterialId"].'">
                        Aflever
                    </a>
                </td>'; 
        }   
        else if (isset($_SESSION["User"])&&$_SESSION["User"]["Admin"]==0&&$borrowed["UserId"]!=$_SESSION["User"]["Id"]) {
            echo'<td>
                   Udlånt
                </td>';
        }
        echo '</tr>';
    }

?>